﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Hopscotch.Common.Contracts.AppService;
using Hopscotch.Domain.Common;
using Hopscotch.Domain.Common.StateTracking;
using Hopscotch.EntityModel.Finance;

namespace Hopscotch.Server.AppService
{
	public abstract class DomainService<T, TKey> : IDomainService<T, TKey>
		where T : DomainBase<TKey>
		where TKey : struct
	{

		public string Ping()
		{
			return "Hello";
		}

		public abstract T Get(TKey id);

		public T Save(T entity)
		{
			using (var context = new FinDbModelContext())
			{
				ValidationContext vc = new ValidationContext(entity, null, null);
				List<ValidationResult> results = new List<ValidationResult>();

				bool valid = Validator.TryValidateObject(entity, vc, results, true);
				if (!valid)
				{
					throw new ApplicationException(results.ToString());
				}

				var objectSet = context.CreateDomainCollection<T>();

				objectSet.ApplyChanges<T>(entity);
				context.SaveChanges();

				return entity;
			}
		}

		public void Delete(T t)
		{
			throw new NotImplementedException();
		}
	}
}
